package avicit.bdp.dds.dao;

import avicit.bdp.dds.dispatch.enums.DbType;
import avicit.bdp.dds.common.utils.ConnectionUtils;
import avicit.bdp.dds.dao.entity.MonitorRecord;
import avicit.bdp.dds.dao.utils.MysqlPerformance;
import avicit.bdp.dds.dao.utils.PostgrePerformance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

/**
 * database state dao
 */
@Component
public class MonitorDBDao {

    private static final Logger logger = LoggerFactory.getLogger(MonitorDBDao.class);

    public static final String VARIABLE_NAME = "variable_name";

    @Autowired
    private DataSource dataSource;

    /**
     * get current db performance
     * @return MonitorRecord
     */
    private MonitorRecord getCurrentDbPerformance(){
        MonitorRecord monitorRecord = null;
        Connection conn = null;
        try{
            conn = dataSource.getConnection();
            String driverClassName = dataSource.getConnection().getMetaData().getDriverName();
            if(driverClassName.contains(DbType.MYSQL.toString().toLowerCase())){
                return new MysqlPerformance().getMonitorRecord(conn);
            } else if(driverClassName.contains(DbType.POSTGRESQL.toString().toLowerCase())){
                return new PostgrePerformance().getMonitorRecord(conn);
            }
        }catch (Exception e) {
            logger.error("SQLException: {}", e.getMessage(), e);
        }finally {
            ConnectionUtils.releaseResource(conn);
        }
        return monitorRecord;
    }

    /**
     * query database state
     * @return MonitorRecord list
     */
    public List<MonitorRecord> queryDatabaseState() {
        List<MonitorRecord> list = new ArrayList<>(1);

        MonitorRecord monitorRecord = getCurrentDbPerformance();
        if(monitorRecord != null){
            list.add(monitorRecord);
        }
        return list;
    }
}
